package dao

import (
	"fmt"
	"strings"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/cashlog"
	"yundian/internel/app/models/wifimodel"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
)

type AdCashDao struct{}

func NewAdCashDao() *AdCashDao {
	return &AdCashDao{}
}

func (dao *AdCashDao) GetCashList(param *request.CashListReq) *dingo.ErrorWrap {

	var (
		lst    []*cashlog.UserWithdrawalLog
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Debug().Table("cash_log w").
		Select("w.*,u.phone,u.name,u.wx_income_qrcode").
		Joins("left join users u on u.id = w.user_id")

	if param.UserId != 2 {
		db.Where("w.user_id=?", param.UserId)
	}
	if param.Name != "" {
		db.Where("u.name like ?", fmt.Sprint("%", param.Name, "%"))
	} // 申请人姓名
	if param.Phone != "" {
		db.Where("u.phone = ?", param.Phone)
	} // 手机号码
	if param.Status > 0 {
		db.Where("w.state = ?", param.Status)
	}

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		db.Where("w.create_at >= ? and w.create_at<= ?", beginTime[0], beginTime[1])
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("w.%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("w.%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		db.Order("w.create_at desc")
	}

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}

func (dao *AdCashDao) InsertCashLog(m *wifimodel.AdCashLogModel) *dingo.ErrorWrap {

	db := global.Orm.Debug().Table("wifi_ad_cash_log").Create(&m)
	return dingo.ErrorIf(db.Error, true)
}








